package flc.ast.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.SeekBar;

import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.reflect.TypeToken;
import com.stark.picselect.entity.SelectMediaEntity;
import com.stark.ve.EditorHolder;
import com.stark.ve.core.IEditorListener;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.bean.RecordBean;
import flc.ast.databinding.ActivityVideoCompressBinding;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.media.MediaMetadataInfo;
import stark.common.basic.utils.FileP2pUtil;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.MediaUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.SPUtil;
import stark.common.basic.utils.TimeUtil;

public class VideoCompressActivity extends BaseAc<ActivityVideoCompressBinding> {

    public static String videoPath;
    private long videoLength;
    private String format;
    private int width,height,bitrate;

    private Handler mHandler;
    private final Runnable mTaskUpdateTime = new Runnable() {
        @Override
        public void run() {
            mDataBinding.tvPlayLeft.setText(TimeUtil.getMmss(mDataBinding.videoView.getCurrentPosition()));
            mDataBinding.sbVideo.setProgress(Integer.parseInt(TimeUtils.millis2String(mDataBinding.videoView.getCurrentPosition(),"ss")));
            mHandler.postDelayed(this, 1000);
        }
    };

    @Override
    protected int onCreate() {
        return R.layout.activity_video_compress;
    }

    @Override
    protected void initView() {
        mDataBinding.ivCompressVideoBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mDataBinding.ivPlayStart.setOnClickListener(this);
        mDataBinding.tvCompressVideoDerive.setOnClickListener(this);
        mDataBinding.tvCompressVideo.setOnClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()){
            case R.id.ivPlayStart://播放暂停
                if (mDataBinding.videoView.isPlaying()) {
                    mDataBinding.ivPlayStart.setImageResource(R.drawable.icon_bf2);
                    mDataBinding.videoView.pause();
                    stopTime();
                } else {
                    mDataBinding.ivPlayStart.setImageResource(R.drawable.icon_zt);
                    mDataBinding.videoView.start();
                    startTime();
                }
                break;
            case R.id.tvCompressVideo:
                videoCompress(width*mDataBinding.sbFbl.getProgress()/100, height*mDataBinding.sbFbl.getProgress()/100, bitrate*mDataBinding.sbBitrate.getProgress()/100);
                break;
            case R.id.tvCompressVideoDerive:
                saveVideo();
                break;
        }
    }

    @Override
    protected void initData() {
        //获取视频路径 时长
        if (TextUtils.isEmpty(videoPath)) return;
        videoLength = MediaUtil.getDuration(videoPath);
        RxUtil.create(new RxUtil.Callback<MediaMetadataInfo>() {
            @Override
            public void doBackground(ObservableEmitter<MediaMetadataInfo> emitter) {
                MediaMetadataInfo mediaMetadataInfo=MediaUtil.getMediaMetadataInfo(videoPath);
                emitter.onNext(mediaMetadataInfo);
            }

            @Override
            public void accept(MediaMetadataInfo info) {
                if (info!=null){
                    width=info.getWidth();
                    height=info.getHeight();
                    bitrate=info.getBitrate();
                }
            }
        });
        String fileName = FileUtils.getFileName(videoPath);
        int i = fileName.lastIndexOf(".");
        format = fileName.substring(i, fileName.length());
    }

    //压缩视频
    private void videoCompress(int width,int height,int bitrate){
        EditorHolder.editor().videoCompress(videoPath, width, height, bitrate, new IEditorListener() {
            @Override
            public void onSuccess(String outFilePath) {
                dismissDialog();
                ToastUtils.showShort(getString(R.string.video_compress_suc));
                String filePath= FileUtil.generateFilePath(Content.myTemp , format);
                FileUtils.copy(outFilePath, filePath);
                videoPath=outFilePath;
                mDataBinding.ivPlayStart.setImageResource(R.drawable.icon_zt);
                mDataBinding.videoView.setVideoPath(videoPath);
                mDataBinding.videoView.seekTo(1);
                mDataBinding.videoView.start();
                startTime();
            }

            @Override
            public void onFailure(String errMsg) {
                ToastUtils.showShort(getString(R.string.video_compress_def));
                dismissDialog();
            }

            @Override
            public void onProgress(int progress) {
                showDialog(getString(R.string.video_compress_ing)+progress+getString(R.string.unit_percent));
            }
        });
    }

    //保存视频
    private void saveVideo(){
        showDialog(getString(R.string.save_video_ing));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                RxUtil.create(new RxUtil.Callback<String>() {
                    @Override
                    public void doBackground(ObservableEmitter<String> emitter) {
                        FileP2pUtil.copyPrivateVideoToPublic(mContext, videoPath);//保存到手机相册
                        dismissDialog();
                        ToastUtils.showShort(getString(R.string.save_to_album));
                        saveRecord(videoPath);
                    }

                    @Override
                    public void accept(String obj) {

                    }
                });
            }
        }, 1000);
    }

    //保存记录
    private void saveRecord(String videoPath) {
        List<RecordBean> listSave = new ArrayList<>();
        String time = TimeUtils.getNowString(new SimpleDateFormat("yyyy/MM/dd"));
        listSave.add(new RecordBean(FileUtils.getFileName(videoPath),
                TimeUtil.getMmss(MediaUtil.getDuration(videoPath)), FileUtils.getSize(videoPath),
                time, videoPath));
        List<RecordBean> listSp = SPUtil.getObject(mContext, new TypeToken<List<RecordBean>>() {
        }.getType());
        if (listSp != null && listSp.size() > 0) {
            listSp.addAll(listSave);
            SPUtil.putObject(mContext, listSp, new TypeToken<List<RecordBean>>() {
            }.getType());
        } else {
            SPUtil.putObject(mContext, listSave, new TypeToken<List<RecordBean>>() {
            }.getType());
        }
    }

    //设置播放器
    private void setPlayer() {
        mHandler = new Handler();
        //设置seekbar
        mDataBinding.sbVideo.setMax(Integer.parseInt(TimeUtils.millis2String(videoLength,"ss")));
        mDataBinding.tvPlayLeft.setText("00:00");
        mDataBinding.tvPlayRight.setText(" / "+TimeUtil.getMmss(videoLength));
        mDataBinding.sbVideo.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                mDataBinding.videoView.seekTo(seekBar.getProgress());
            }
        });
        //设置播放器
        mDataBinding.videoView.setVideoPath(videoPath);
        mDataBinding.videoView.seekTo(1);
        mDataBinding.videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {  // 播放完成的监听
                mDataBinding.tvPlayLeft.setText("00:00");
                mDataBinding.sbVideo.setProgress(0);
                mDataBinding.ivPlayStart.setImageResource(R.drawable.icon_bf2);
                mp.seekTo(1);
                stopTime();
            }
        });
    }

    private void startTime() {
        mHandler.post(mTaskUpdateTime);
    }

    private void stopTime() {
        mHandler.removeCallbacks(mTaskUpdateTime);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //设置播放器
        setPlayer();
        //直接播放视频
        mDataBinding.videoView.seekTo(1);
        mDataBinding.ivPlayStart.setImageResource(R.drawable.icon_zt);
        mDataBinding.videoView.start();
        startTime();
    }

    @Override
    protected void onStop() {
        super.onStop();
        stopTime();
    }

    @Override
    protected boolean isStatusBarTextDark() {
        return false;
    }
}